package com.sjgtw.cloud.web.keysArea.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.sjgtw.cloud.common.core.web.controller.BaseController;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.core.web.page.TableDataInfo;
import com.sjgtw.cloud.util.EasyExcelUtil;
import com.sjgtw.cloud.web.keysArea.domain.KeysAreas;
import com.sjgtw.cloud.web.keysArea.service.IKeysAreasService;
import com.sjgtw.cloud.web.warningSign.domain.WarningSigns;
import com.sjgtw.cloud.web.warningSign.service.IWarningSignsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 防洪重点地段管理Controller
 * 
 * @author ruoyi
 * @date 2024-03-15
 */
@RestController
@Api(tags = "1.7、防洪重点地段管理")
@RequestMapping("/keysAreas")
public class KeysAreasController extends BaseController
{
    @Autowired
    private IKeysAreasService keysAreasService;
    @Autowired
    private IWarningSignsService warningSignsService;

    /**
     * 查询防洪重点地段管理列表
     */

    @GetMapping("/list")
    @ApiOperation("list列表")
    public TableDataInfo list(KeysAreas keysAreas)
    {
        startPage();
        List<Map<String,Object>> list = keysAreasService.selectKeysAreasList(keysAreas);
        return getDataTable(list);
    }

    /**
     * 导出防洪重点地段管理列表
     */


/*    @PostMapping("/export")
    public void export(HttpServletResponse response, KeysAreas keysAreas)
    {
        List<KeysAreas> list = keysAreasService.selectKeysAreasList(keysAreas);
        ExcelUtil<KeysAreas> util = new ExcelUtil<KeysAreas>(KeysAreas.class);
        util.exportExcel(response, list, "防洪重点地段管理数据");
    }*/

    /**
     * 获取防洪重点地段管理详细信息
     */

    @GetMapping(value = "/getInfo/{id}")
    @ApiOperation("获取详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(keysAreasService.selectKeysAreasById(id));
    }

    /**
     * 新增防洪重点地段管理
     */

    @PostMapping("/add")
    @ApiOperation("新增,多组位置和左右侧，分别将位置逗号拼接，左右侧拼接传回")
    public AjaxResult add(@RequestBody KeysAreas keysAreas)
    {
        return toAjax(keysAreasService.insertKeysAreas(keysAreas));
    }

    /**
     * 修改防洪重点地段管理
     */

    @PutMapping("/edit")
    @ApiOperation("修改")
    public AjaxResult edit(@RequestBody KeysAreas keysAreas)
    {
        return toAjax(keysAreasService.updateKeysAreas(keysAreas));
    }

    /**
     * 删除防洪重点地段管理
     */

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(keysAreasService.deleteKeysAreasById(id));
    }


    /**
     * 导出
     */
    @ApiOperation(value = "导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response, KeysAreas keysAreas, Boolean withWarning)
    {
        List<KeysAreas> areas = keysAreasService.selectKeysAreasList2(keysAreas);
        List<WarningSigns> signs = warningSignsService.selectWarningSignsList2(new WarningSigns());
        Map<Long, List<WarningSigns>> signsMap = signs.stream().filter(e -> e.getKeysAreasId() != null).collect(Collectors.groupingBy(WarningSigns::getKeysAreasId));

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("防洪重点地段", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            String template = "keysAreas";
            if (withWarning != null && withWarning) {
                template = "keysAreasAndWarning";
            }
            final ClassPathResource classPathResource = new ClassPathResource("template/" + template + ".xlsx");
            InputStream inputStream = classPathResource.getInputStream();

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build();
            if (areas != null) {
                addNum(areas);
            }
            WriteSheet writeSheet1 = EasyExcel.writerSheet("防洪重点地段").build();
            excelWriter.fill(areas, writeSheet1);

            if (withWarning != null && withWarning) {
                for (KeysAreas area : areas) {
                    List<WarningSigns> warningSigns = signsMap.get(area.getId());
                    if (warningSigns != null) {
                        for (WarningSigns sign : warningSigns) {
                            sign.setKeysAreasNum(area.getNum());
                        }
                    }
                }

                // 对List<WarningSigns>按照keysAreasNum升序排序，空值放在最后
                signs.sort(Comparator.comparing(
                        WarningSigns::getKeysAreasNum,
                        Comparator.nullsLast(Integer::compareTo)
                ));


                if (signs != null) {
                    addNum2(signs);
                }
                WriteSheet writeSheet2 = EasyExcel.writerSheet("防洪警示标志").build();
                excelWriter.fill(signs, writeSheet2);
            }

            // 千万别忘记关闭流
            excelWriter.finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void addNum2(List<WarningSigns> entities) {
        for (int i=0; i<entities.size(); i++)
            entities.get(i).setNum(i+1);
    }

    private void addNum(List<KeysAreas> entities) {
        for (int i=0; i<entities.size(); i++)
            entities.get(i).setNum(i+1);
    }

    /**
     * 下载模版
     */
    @ApiOperation(value = "下载模版")
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response, Boolean withWarning)
    {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("防洪重点地段模版", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            String template = "keysAreas";
            if (withWarning != null && withWarning) {
                template = "keysAreasAndWarning";
            }
            final ClassPathResource classPathResource = new ClassPathResource("template/" + template + ".xlsx");
            InputStream inputStream = classPathResource.getInputStream();

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build();
            WriteSheet writeSheet1 = EasyExcel.writerSheet("防洪重点地段").build();
            excelWriter.fill(new ArrayList<>(), writeSheet1);

            if (withWarning != null && withWarning) {
                WriteSheet writeSheet2 = EasyExcel.writerSheet("防洪警示标志").build();
                excelWriter.fill(new ArrayList<>(), writeSheet2);
            }
            // 千万别忘记关闭流
            excelWriter.finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入
     */
    @ApiOperation(value = "导入")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, Boolean withWarning)
    {
        EasyExcelUtil<KeysAreas> util = new EasyExcelUtil<>(KeysAreas.class);
        List<KeysAreas> areas = util.readExcel(file, 0, 2);
        if (areas == null || areas.size() == 0) {
            return error("没有读取到数据");
        }
        areas = areas.subList(0, areas.size());
        List<String> errors = keysAreasService.check(areas);

        List<WarningSigns> signs = new ArrayList<>();
        if (withWarning != null && withWarning) {
            EasyExcelUtil<WarningSigns> util2 = new EasyExcelUtil<>(WarningSigns.class);
            signs = util2.readExcel(file, 1, 1);
            List<String> errors2 = warningSignsService.check(signs);
            errors.addAll(errors2);
        }

        if (errors.size() > 0) {
            return AjaxResult.error("", errors);
        }

        Map<Integer, List<WarningSigns>> signsMap = signs.stream().filter(e -> e.getKeysAreasNum() != null).collect(Collectors.groupingBy(WarningSigns::getKeysAreasNum));

        for (KeysAreas area : areas) {
            keysAreasService.insertKeysAreas(area);
            List<WarningSigns> warningSigns = signsMap.get(area.getNum());
            if (warningSigns != null) {
                for (WarningSigns sign : signs) {
                    sign.setKeysAreasId(area.getId());
                }
            }
        }
        if (withWarning != null && withWarning && signs.size() > 0)
            warningSignsService.batchSave(signs);
        return success();
    }

}
